package com.gmlive.common.sample

import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.ImageView
import android.widget.Toast
import com.gmlive.common.host.helper.ApiUrlHelper
import com.gmlive.common.host.manager.HostUpdateManager
import com.gmlive.common.network.domain.DomainManager
import com.gmlive.common.sample.dialog.DialogDemoActivity
import com.gmlive.common.sample.host.HttpHost
import com.gmlive.common.sample.http.HttpLogActivity
import com.gmlive.common.ui.app.IkCompatActivity
import com.meelive.ingkee.photoselector.util.PhotoSelectorUtil
import com.meelive.ingkee.photoselector.widget.cropimage.CropImageView
import com.meelive.ingkee.push.InkePushManage
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File

class MainActivity : IkCompatActivity() {
    var image: ImageView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (!InkePushManage.isNotificationEnabled(this)) {
            InkePushManage.openPushSwitch(this)
        }
        image = findViewById(R.id.image)

        sample_http_logger.setOnClickListener {
            gotoHttpLoggerSample()
        }

        sample_dialog.setOnClickListener {
            gotoDialogSample()
        }

        sample_photo_selector_single.setOnClickListener {
            gotoSinglePhotSelectorSample()
        }

        sample_photo_selector_multiple.setOnClickListener {
            gotoMultiplePhotSelectorSample()
        }

        sample_take_photo.setOnClickListener {
            gotoTakePhotoSample()
        }

        sample_crop_photo.setOnClickListener {
            gotoCropPhotoSample()
        }

        host.setOnClickListener {
            // requestHost()
            DomainManager.getInstance().setPrepareCallback { success, fromCache ->
                Log.i("DomainManager", "domain prepared: success = $success, fromCache = $fromCache");

                Log.i("DomainManager", "Get value for App = ${DomainManager.getInstance().getDomainForKey("App")}")
            }

            DomainManager.getInstance().startRefreshDomain()
        }

        host_thred.setOnClickListener {
            requestHostThred()
        }

        host_test.setOnClickListener {
            doHostTest()
        }

        camerax.setOnClickListener {
            gotoTakePhotoFront()
        }
    }

    fun gotoHttpLoggerSample() {
        val intent = Intent(this, HttpLogActivity::class.java)
        startActivity(intent)
    }

    fun gotoDialogSample() {
        val intent = Intent(this, DialogDemoActivity::class.java)
        startActivity(intent)
    }

    fun gotoSinglePhotSelectorSample() {
        PhotoSelectorUtil.selectSinglePhoto(this, true, CropImageView.DEFAULT_SCALE_SIZE, 4) { selectedList ->
            for (info in selectedList) {
                Log.i("ziq", "onActivityResult: " + info.path)
            }
        }
    }

    fun gotoMultiplePhotSelectorSample() {
        PhotoSelectorUtil.selectMultiplePhoto(this, 3, 9) { selectedList ->
            for (info in selectedList) {
                Log.i("ziq", "onActivityResult: " + info.path)
            }
        }
    }

    fun gotoTakePhotoSample() {
        val imageCaptureUri = imageCaptureUri
        PhotoSelectorUtil.takePhoto(this, imageCaptureUri, true, CropImageView.DEFAULT_SCALE_SIZE) { selectedList ->
            for (info in selectedList) {
                Log.i("ziq", "onActivityResult: " + info.path)
            }
        }
    }

    fun gotoCropPhotoSample() {
        val url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1570517899326&di=ef23a01fcaa967942a0a319f4de2bf08&imgtype=0&src=http%3A%2F%2Fpic38.nipic.com%2F20140228%2F2457331_083845176000_2.jpg"
        //String url = "http://pic1.win4000.com/mobile/2019-03-29/5c9dda67deb87.jpg";
        //String url = "https://s2.ax1x.com/2019/12/19/Qb3lPf.jpg";
        PhotoSelectorUtil.showCrop(this, url, CropImageView.DEFAULT_SCALE_SIZE) { selectedList ->
            for (info in selectedList) {
                Log.i("ziq", "onActivityResult: " + info.path)
                image!!.setImageURI(Uri.fromFile(File(selectedList[0].path)))
            }
        }
    }

    fun gotoTakePhotoFront() {
        val rootPath = Environment.getExternalStorageDirectory().absolutePath
        val path = if (rootPath.endsWith("/")) rootPath else rootPath + "/" + "tmp_img_" + System.currentTimeMillis().toString() + ".jpg"
        PhotoSelectorUtil.takePhotoFront(this, path, false, CropImageView.DEFAULT_SCALE_SIZE) { selectedList ->
            for (info in selectedList) {
                Log.i("ooo", "onActivityResult: " + info.path)
            }
        }
    }

    /**
     * 获取照相以后 图片存储的位置uri
     */
    val imageCaptureUri: Uri?
        get() {
            var uri: Uri? = null
            try {
                val rootPath = Environment.getExternalStorageDirectory().absolutePath
                val pa = if (rootPath.endsWith("/")) rootPath else rootPath + "/" + "tmp_img_" + System.currentTimeMillis().toString() + ".jpg"
                val values = ContentValues()
                values.put(MediaStore.Images.Media.TITLE, pa)
                uri = try {
                    contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                } catch (e: Exception) {
                    contentResolver.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values)
                }
            } catch (e: Exception) {
            }
            return uri
        }

    fun requestHost() {
//        for (index in 0..2000) {
            HostUpdateManager.ins().getUpdateHost(null)
//        }
    }

    fun requestHostThred() {
        for (index in 0..2000) {
            Thread(Runnable { HostUpdateManager.ins().getUpdateHost(null) }).start()
        }
    }

    fun doHostTest() {
        if (!HostUpdateManager.ins().isHostInit) {
            Toast.makeText(this, "请先初始化host", Toast.LENGTH_SHORT).show()
            return
        }
        Log.i("ziq", "当前环境是否测试环境：" + HostUpdateManager.ins().isTest)
        Log.i("ziq", "替换App：前：" + HttpHost.ROOM_PK_SWITCH_ALLOW + " 后：" + ApiUrlHelper.getInstance().getUrl(HttpHost.ROOM_PK_SWITCH_ALLOW))
        Log.i("ziq", "替换ImageScale：前：" + HttpHost.IMAGE_SCALE + " 后：" + ApiUrlHelper.getInstance().getUrl(HttpHost.IMAGE_SCALE))
        Log.i("ziq", "替换M4aik：前：" + HttpHost.BZ_MEDIAURL + " 后：" + ApiUrlHelper.getInstance().getUrl(HttpHost.BZ_MEDIAURL))
        Log.i("ziq", "替换Img2ik：前：" + HttpHost.IMAGE + " 后：" + ApiUrlHelper.getInstance().getUrl(HttpHost.IMAGE))
        Log.i("ziq", "替换Pay：前：" + HttpHost.PAYMENT_INFO + " 后：" + ApiUrlHelper.getInstance().getUrl(HttpHost.PAYMENT_INFO))
        Log.i("ziq", "替换Serviceik：前：" + HttpHost.LINK_TIME_GETCONFIG + " 后：" + ApiUrlHelper.getInstance().getUrl(HttpHost.LINK_TIME_GETCONFIG))
        Log.i("ziq", "替换Upload：前：" + HttpHost.IMAGE_UPLOAD + " 后：" + ApiUrlHelper.getInstance().getUrl(HttpHost.IMAGE_UPLOAD))
        Log.i("ziq", "替换Vocik：前：" + HttpHost.VOICE_DOWNLOAD + " 后：" + ApiUrlHelper.getInstance().getUrl(HttpHost.VOICE_DOWNLOAD))
        Log.i("ziq", "H5：" + ApiUrlHelper.getInstance().h5Host)
    }
}